package com.springcloud.security;

import com.springcloud.model.SysRole;
import com.springcloud.model.vo.UserVo;
import com.springcloud.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 自定义的UserDetailsService,实现loadUserByUsername方法
 * 查询用户,如果查询到返回用户和用户所拥有的角色
 */
@Service
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private ISysUserService userService;

    /**
     *
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = userService.selectVoByLoginName(username);
        if (userVo == null ) {
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        StringBuilder roleIds = new StringBuilder();
        Iterator<SysRole> iRole = userVo.getRolesList().iterator();
        while (iRole.hasNext()){
            roleIds.append(","+iRole.next().getId());
        }
        String roles = roleIds.toString().substring(1);
        authorities.add(new SimpleGrantedAuthority(userVo.getId().toString()+"/"+roles));

        return new User(userVo.getLoginName(), userVo.getPassword(),authorities);
    }
}
